# -*- coding: utf-8 -*-
import datetime
import math
import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time, urljoin, json
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class SichuanLeshanPolicy(BaseTaxPolicySpider):
    name = 'sichuan_leshan2_policy'

    province = '四川省'
    city = '乐山市'
    # county = ''
    park = ''

    def __init__(self, get_next=False, **kwargs):
        super().__init__(**kwargs)
        print(get_next)
        self.get_next = get_next

    @classmethod
    def update_settings(cls, settings) -> None:
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                # "COOKIES_ENABLED": False,
                "DOWNLOAD_TIMEOUT": 200,
                # "CONCURRENT_REQUESTS": 2,
                "HTTPERROR_ALLOWED_CODES": [302, 400, 404, 500, 200, 202, 502, 429, 403],
                # "DOWNLOAD_DELAY": 5,
                # "DOWNLOADER_MIDDLEWARES": {
                #     "components.middlewares.downloadmiddlewares.public.company_ip_by_api.CompanyIpByApiMiddleware": None,
                # },
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            ['乐山市发展和改革委员会', "", "https://sfgw.leshan.gov.cn/govinfo2/channel/index/33"],
            ['乐山市经济和信息化局', "", "https://sjxj.leshan.gov.cn/sjxw/wjfb/flfg.shtml"],
            ['乐山市科学技术局', "", "https://skjj.leshan.gov.cn/skjj/zcfg/xxgkzcwj.shtml"],
            ['乐山市财政局', "", "https://sczj.leshan.gov.cn/sczj/xzgfxwj/xxgkzcwj.shtml"],
            ['乐山市市场监督管理局', "", "https://scjgj.leshan.gov.cn/scjgj/zcfg/xzcwj.shtml"],
        ]:
            item = {'source': source, 'county': county}
            if 'shtml' in url:
                callback = self.parse_url
            else:
                callback = self.parse_content
            yield scrapy.Request(url, callback=callback, meta={'item': item}, dont_filter=True)

    def parse_url(self, response, **kwargs):
        url = response.xpath("//script[contains(@src, '" + response.url.split("/")[-1].split(".")[0] + "')]/@src").get()
        yield response.follow(url, callback=self.parse_content, meta=response.meta, dont_filter=True)

    def parse_content(self, response, **kwargs):
        meta = response.meta
        regionId = response.xpath('.').re_first(r"region[iI]+d'?\s*[:=]+\s*['\"]?(\d+)['\"]?[;,]+")
        channelId = response.xpath('.').re_first(r"channelId'?\s*[:=]+\s*['\"]?(\d+)['\"]?[;,]+") or response.xpath('.').re_first(r"chId'?\s*[:=]+\s*['\"]?(\d+)['\"]?[;,]+")
        deptId = response.xpath('.').re_first(r"deptId'?\s*[:=]+\s*['\"]?(\d+)['\"]?[;,]+")
        print(response.url, deptId, regionId, channelId)
        if 'governfile' in response.text:
            url = '/open-information/document/governfile.do'
        else:
            url = '/open-information/document/list.do'
        detail_url = response.xpath(".").re_first(r"\"(/.*xxgkcontent.*?shtml.*?)\'") or response.xpath(".").re_first(r"\"(/.*xxgkcontent.*?shtml.*?)\{\{=")
        formdata = {
            'pageSize': '70',
            'pageNo': '1',
            'regionId': regionId,
            'deptId': deptId,
            'channelId': channelId,
        }
        meta['data'] = formdata
        meta['detail_url'] = detail_url
        # 生成初始请求
        yield scrapy.FormRequest(
            url=response.urljoin(url),
            method='POST',
            formdata=formdata,
            callback=self.parse_list,
            meta=meta  # 携带页码信息
        )

    def parse_list(self, response, **kwargs):
        meta = response.meta
        prev_item = meta.get('item')
        data = meta['data']
        json_datas = response.json()['data']
        elem_list = json_datas['dataList']
        for elem in elem_list:
            item = Item()
            item['source_url'] = meta['detail_url'] + elem['id']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = str(datetime.datetime.fromtimestamp(elem['pubTime'] / 1000)).split(' ')[0]
            item['title'] = elem['title']
            if item['publish_date'] < '2022-01-01':
                # self.get_next = None
                pass
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            # if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
            #     continue
            if 'relativeInfo' in item['source_url']:
                continue
            print(json.dumps(data, separators=(',', ':')), item['source_url'])
            yield scrapy.FormRequest(response.urljoin('/open-information/document/info.do'),
                                     formdata={'id': elem['id']},
                                     callback=self.parse_detail, meta={'item': item})
        if (self.get_next or self.get_next == '0') and meta.get('is_next') is not False:
            total_page = json_datas['totalPage']
            print(json.dumps(data, separators=(',', ':')), total_page, 'total', json_datas['total'])
            for page_num in range(2, total_page + 1):
                data['pageNo'] = str(page_num)
                meta.update({'item': prev_item, 'is_next': False})
                yield scrapy.FormRequest(response.url, callback=self.parse_list, meta=meta, formdata=data)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        # item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        # item['publish_date'] = response.xpath(
        #     """string(//meta[@name='PubDate']/@content)""").get() or response.xpath(
        #     "//*[@class='fbrq']/text()").get()
        item['content'] = response.text
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl sichuan_leshan2_policy -a get_next=0".split())
